<?php
namespace frontend\controllers;

use Yii;
use common\models\Goods;
use frontend\controllers\base\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\Goodsfile;
use common\models\Record;
use common\models\Column;
use common\models\Cart;
use common\models\Collect;
use common\models\search\GoodsSearch;
use yii\data\Pagination;
use common\models\Address;
use common\models\District;
use common\models\Order;
use common\models\Oinfo;
use vendor\pay\lib\PaySubmit;
use vendor\pay\lib\PayNotify;
use common\models\GoodsType;

/**
 * GoodsController implements the CRUD actions for Goods model.
 */
class GoodsController extends BaseController
{
    public $payConfig=[
        //MustPay平台公钥
        'plate_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO7CQpYHhEonv1g9YjRVGJDaCOu0bXogD7pBLQu2dDvJ8TGROCEw6ArIWgAWEEE1uEShPBa4MpCP4ZMjT5RMj45o0pb0Z8s4k6CpS9D1LFK9msNpsN8PyaRDQC86R6jxAVQMWgfIZ9cxfZR8Ple3GJGjwBfeRnzh75rE1DHCBOcwIDAQAB',
        //商户私钥
        'mer_private_key'=>'MIICXAIBAAKBgQDMZzQy4iu8s+7KN7VymVEgZlTzfwQbCmtAM+v6rj4YBrdm6qJQ
u8xs/JPjEvd+2oBw6y41YmIjKXOT7Dw1h6KOdq0wdcrR5gnq1qWv47Kegh38At2I
UcI2flV3Hhw68tT0I++Hn9Li9t6ZgsmOjJ+oDe6ykcGxl62Ttgd2as57uwIDAQAB
AoGAf52rrF0i+3THkH9JjNwGF5lsTn4tvQg7P+Fq4p7o66090kaJwqgNkLn9Rxdv
aEbZTCa5OeFL7jISE/e4+57MMNEW7BMa0BrIBvmdwwHykfQ9iH34ye+uHFh4GrgB
wDhXbcGpdxqJ1HHd37m04MQDzqmLe1JwEFsWlI9Nv6Ryw+kCQQD73OxDRvZQstLw
dYoDme1PQGz/Hj7km/+aZNWyaQqu4mXzd0c4c9HBxaZ0pFL+YHfW9hWSZfb8JosS
TI62SrinAkEAz8K2sT4Yf/Xvxy0I1yiQ0nesD4ubr05RoJkDLDFenQ5D4Sdhcdhj
cHuZa4b2qk3P3INFrNG6pn7iNmNtFNgyzQJAJOmjAtUyom8i9TT0zkRQAG57ywQe
yZiHZJRksWots6XgtUcE/CQVWOXj2HKA62EuDyYv0S36fcgUV9E6lULsPwJBAIS2
BUsstiuu5q5dBwOhRvkaNo9rh1Qw/BVRCGTHWH+MaDG/nRBCwCpO2Y6FFLVupPNf
6zbcdZT7AfbqBfjFrZUCQBFRJQBbXk7FSVMEwWvhiaeH/4fmC2XCleRK/NsvJ942
u0xz6he+1tcR1CR9rhH90Qc1b7wncOd+sztMmlKghnY=
',
    //测试商户apps_id
        'apps_id'=>'8cda6b585512455a9ffe79b99ee9bf02',
        //测试商户mer_id
        'mer_id' => '17033016380467631',
        //异步回调URL 此地址必须外网可访问
        'notify_url' => 'http://www.daojianchang.com/pay/pay-notify.html',
        //同步回调URL 此地址必须外网可访问
        'return_url'=> 'http://www.daojianchang.com/pay/pay-return.html',
        // 签名方式
        'sign_type' => 'RSA',
    // 字符编码格式 目前支持utf-8
        'input_charset' => 'utf-8',
    //下单地址
        'add_order_url' => 'https://www.mustpay.com.cn/service/order/saveOrder',
    //订单查询地址
        'query_order_url' => 'https://www.mustpay.com.cn/service/order/queryOrder',
    //ca证书路径地址，用于curl中ssl校验
    //请保证cacert.pem文件在当前文件夹目录中
        'cacert' => '/var/www/vendor/pay/cacert.pem',
        
    ];
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ],
                    'collect'=>[
                        'POST'
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all Goods models.
     * 
     * @return mixed
     */
    public function actionIndex()
    {
        $get = Yii::$app->request->get();
        $get['GoodsSearch']['name']=htmlspecialchars($get['GoodsSearch']['name']);
        $goods = [];
        $search=new GoodsSearch();
        if (isset($get['pid'])){
            $pid=$parent = max((int) $get['pid'], 1);
        }
        $order='look desc';
        if(isset($get['o'])){//综合、价格等筛选条件
            switch ($get['o']){
                case 1:$order='num desc';break;
                case 2:$order='price desc';break;
                case 3:$order='price asc';break;
                case 4:$order='id desc';break;
            }
        }
        $hot=Goods::find()->where('hot=1')->select('id,name,price,logo,look')->asArray()->all();//推荐宝贝
        $cdata=$this->columnData();//未重组前分类数组
        $column = Yii::$app->view->params['column'];//无限极分类后的分类数组 
        if(!empty($cdata)){
            $cdata=array_column($cdata, null,'id');
        }
        if (isset($column[$pid])) {
            $search->pid = array_column($column[$pid], 'id');
        }else{
            if(!empty($cdata)){
                $search->pid=$pid;
                if(isset($cdata[$pid]['pid']) && isset($cdata[$cdata[$pid]['pid']])){
                    $parent=$cdata[$cdata[$pid]['pid']]['id'];
                }
            }
        }
        $model=$search->search(Yii::$app->request->queryParams)->query;
        $pages=new Pagination(['totalCount'=>$model->count(),'pageSize'=>30]);//分页
        $goods =$model->offset($pages->offset)->limit($pages->limit)->orderBy($order)
            ->asArray()
            ->all();
        $this->showCart();//加载购物车
        return $this->render('index', [
            'goods' => $goods,
            'pid' => $pid,
            'pages'=>$pages,
            'cdata'=>$cdata,
            'hot'=>$hot,
            'parent'=>$parent,
            'get'=>$get,
            'colors'=>$colors
        ]);
    }

    /**
     * Displays a single Goods model.
     * 
     * @param integer $id            
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);

        $colors=GoodsType::find()->where('gid='.$model->id)->asArray()->all();
        $model->look += 1;
        $model->save([
            'look' => $model->look
        ]);
        if (! Yii::$app->user->isGuest) {
            $uid = Yii::$app->user->id;
            $record = Record::find()->where('uid=' . $uid)->count();
            //查询当前商品是否已经存在浏览记录中
            if (! Record::find()->where(['uid' => $uid,'pid' => $model->id])->select('pid')->one()) {
                if ($record >= 9) {
                    Record::find()->where('uid=' . $uid)
                        ->orderBy('createtime')
                        ->one()
                        ->delete();
                }
                Yii::$app->db->createCommand()
                    ->insert('record', [
                    'uid' => $uid,
                    'pid' => $model->id,
                    'createtime' => time()
                ])
                    ->execute();
            }
        }
        $imgs = Goodsfile::find()->where('pid=' . $id)->all();//查询副图
        $similar=Goods::find()->where('pid='.$model->pid)->orderBy('look desc')->limit(3)->asArray()->all();
        $hot=Goods::find()->select('id,name,logo,price')->orderBy('sum desc')->limit(9)->asArray()->all();
        $this->showCart();
        $this->columnData();
        return $this->render('view', [
            'model' => $model,
            'imgs' => $imgs,
            'similar'=>$similar,
            'hot'=>$hot,
            'col' => Column::findOne($model->pid),
            'colors'=>$colors
        ]);
    }
    /**
     * 订单管理
     */
    public function actionOrder(){
        if(Yii::$app->user->isguest){
            return $this->redirect('/site/login.html');
        }
        $post=Yii::$app->request->post();
        $flag=false;
        if(isset($post)){
            if(isset($post['ids'])){
                $data=Cart::find()->with('goods')->orderBy('id desc')->where('id in ('.implode(',', $post['ids']).') and uid='.Yii::$app->user->id)->asArray()->all();
                if(!empty($data)) $flag=1;
            }elseif(isset($post['oid'])){
                $data=Goods::find()->where('id='.$post['oid'])->asArray()->one();
                if(!empty($data)) $flag=2;
            }
            $address=Address::find()->where('uid='.Yii::$app->user->id)->orderBy('status desc,id desc')->asArray()->all();
            if(!empty($address)){
                $district=$this->area($address);
            }
        }
        $this->showCart();
        $this->columnData();
        return $this->render('order',[
            'address'=>$address,
            'data'=>$data,
            'flag'=>$flag,
            'district'=>$district
        ]);
    }
    public function actionCreateOrder(){
        if(Yii::$app->user->isguest){
            return $this->redirect('/site/login.html');
        }
        $model=new Order();
        $info=new Oinfo();
        $model->uid=Yii::$app->user->id;
        $model->status=0;
        $model->create_at=time();
        $post=Yii::$app->request->post();
        $model->omun=date('YmdHis').rand(1000, 9999);
        if(isset($post['did'])){
            $address=Address::find()->where('id='.$post['did'])->asArray()->one();
            if(!empty($address)){
                $model->phone=$address['phone'];
                $model->tel=$address['tel'];
                $model->name=$address['name'];
                $model->address=$address['address'];
                $model->province=$address['province'];
                $model->city=$address['city'];
                $model->flag=md5(date('YmdHis').rand(100000, 999999));
                $model->community=$address['community'];
                if(isset($post['gid'])){//判断是否是直接下单
                    $goods=Goods::find()->select('id,logo,name,price')->where('id='.$post['gid'])->asArray()->one();
                    if(!empty($goods)){
                        $num=max($post['num'],1);
                        $model->price=$goods['price']*$num;
                        $model->type='图色';
                        if(isset($post['tid'])){
                            $type=GoodsType::find()->where('id='.(int)$post['tid'].' and gid='.$goods['id'])->asArray()->one();
                            if(!empty($type)){
                                $model->price=$type['price']*$num;
                                $model->type=$type['name'];
                            }
                        }
                        if($model->save()){//插入主订单生成子订单数组
                            $info->name=$goods['name'];
                            $info->price=$goods['price'];
                            $info->num=$num;
                            $info->logo=$goods['logo'];
                            $info->gid=$goods['id'];
                            $info->oid=$model->id;
                            if($info->save()){
                                $this->redirect(['/goods/pay','id'=>$model->omun]);
                            }
                        }
                    }
                }elseif(!empty($post['cid'])){//判断是否为购物车提交
                    $cart=Cart::find()->with('goods')->where('id in ('.implode(',', $post['cid']).') and uid='.Yii::$app->user->id)->asArray()->all();
                   $infos=[];
                   $price=0;
                   if(!empty($cart)){
                        foreach($cart as $val){
                            $price+=$val['num']*$val['goods']['price'];
                            $infos[]=[//子订单数据
                                'id'=>null,
                                'gid'=>$val['gid'],
                                'num'=>$val['num'],
                                'price'=>$val['goods']['price'],
                                'name'=>$val['goods']['name'],
                                'logo'=>$val['goods']['logo'],
                            ];
                        }
                        $model->price=$price;
                        $model->flag=md5(date('YmdHis').rand(100000, 999999));
                        if(!empty($infos)){
                            if($model->save()){
                                foreach($infos as $key=>$val){//为子订单数据分配主订单id
                                    $infos[$key]['oid']=$model->id;
                                }
                                if($this->insertAll($info, $infos)){
                                    $this->redirect(['/goods/pay','id'=>$model->omun]);
                                    Cart::deleteAll('id in ('.implode(',', $post['cid']).') and uid='.Yii::$app->user->id);
                                }
                            }
                        }
                    }
                }
            }
            
        }
        
    }
    /**
     * 订单支付
     * @param unknown $id 订单号
     */
    public function actionPay($id){
        if(Yii::$app->user->isguest){
            return $this->redirect('/site/login.html');
        }
        $this->showCart();
        $this->columnData();
        $order=Order::find()->where('omun='.$id)->one();
        if($order){
            $info=Oinfo::find()->where('oid='.$order->id)->asArray()->all();
        }
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $order->omun;   
        //商品名称，必填
        $subject = '锐锋刀剑网在线支付';
        
        //付款金额，必填（单位：分）
        $total_fee = $order->price*100;
        //////////////////////////////////////////////////////////////////////////////////
        //构造要请求的参数数组，无需改动
        $parameter = array(
            'apps_id' => $this->payConfig['apps_id'],
            'out_trade_no' => $out_trade_no,
            'mer_id' => $this->payConfig['mer_id'],
            'total_fee' => $total_fee,
            'subject' => $subject,
            'notify_url' => $this->payConfig['notify_url'],
            'return_url' => $this->payConfig['return_url'],
            'user_id' => $order->uid,     //用户在商户平台的唯一标示
            'extra' => $order->flag     //扩展字段，在异步通知时会原样返回给商户
        );
        //建立请求
        $mustpaySubmit = new PaySubmit($this->payConfig);
        $prepayId = $mustpaySubmit->requestPrepayId($parameter);
        return $this->render('pay',[
            'order'=>$order,
            'info'=>$info,'prepayId'=>$prepayId,
            'apps_id'=>$this->payConfig['apps_id']
            
        ]);
    }
    
    /**
     * Finds the Goods model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * 
     * @param integer $id            
     * @return Goods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Goods::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionCart()
    {
        $flag = false;
        if ($uid = Yii::$app->user->id) {
            $num = 1;
            $post = Yii::$app->request->post();
            $goods = [];
            if (isset($post['num']))
                $num = max((int) $post['num'], 1);
            if (isset($post['pid'])) {
                $model = new Cart();
                $pid = (int) $post['pid'];
                $cart = $model->find()->where(['gid' => $pid,'uid' => $uid])->one();
                if (empty($cart)) {
                    $goods = Goods::find()->select('id')->where('id=' . $pid)->one();
                    if (! empty($goods)) {
                        $model->gid = $goods->id;
                        $model->uid = $uid;
                        $model->created_at = time();
                        $model->num = $num;
                        if ($model->save(false))
                            $flag = 1;
                    }
                } else {
                    $cart->num = $cart->num + $num;
                    if ($cart->save(false))
                        $flag = 2;
                }
            }
        }
        return json_encode([
            0 => $flag
        ]);
    }

    public function actionCollect()
    {
        $flag = 0;//未登录
        if ($uid = Yii::$app->user->id) {
            $post = Yii::$app->request->post();
            $pid = (int) $post['id'];
            $model = new Collect();
            $data = $model->find()
                ->where([
                'gid' => $pid,
                'uid' => $uid
            ])
                ->one();
            if (empty($data)) {
                $goods = Goods::find()->select('id')
                    ->where('id=' . $pid)
                    ->one();
                if (! empty($goods)) {
                    $model->uid = $uid;
                    $model->gid = $pid;
                    if($model->save()){
                        $flag=1;//收藏成功
                    }else{
                        $flag=2;//收藏失败
                    }
                }else{
                    $flag=3;//商品不存在
                }
            }else{
                $flag=4;//已收藏
            }
        }
        return json_encode([
            0 => $flag
        ]);
    }
    /**
     * 返回省市区数据
     * @param unknown $data
     * @return \yii\db\ActiveRecord[]
     */
    public function area($data){
        $district=[];
        $province=array_column($data,'province');
        $city=array_column($data, 'city');
        $community=array_column($data, 'community');
        $ids=array_unique(array_merge($province,$city,$community));
        $district=District::find()->where('id in ('.implode(',', $ids).')')->asArray()->all();
        if(!empty($district)) $district=array_column($district,'name','id');
        return $district;
    }
}
